var db = null;

var dbSupport = window.openDatabase;

function insertBlog(title, description, callback) {
	if (dbSupport)
	{
		var createdAt = new Date().getTime();
		
		var guid = 'guid-' + new Date().getTime();
		
		db.transaction(function(tx) {
	    	tx.executeSql('INSERT INTO blogs (guid, title, description, createdAt, isDeleted, isSync) VALUES (?, ?, ?, ?, ?, ?)', [guid, title, description, createdAt, 0, 0], callback);
		});
	}
}

function getNotSyncData(){
	
	var result = {};
	
    db.transaction(function(tx) {
    	tx.executeSql('SELECT * FROM blogs WHERE isSync = 0', [], function(tx, rs){
    		if (rs !== null)
    		{
    			for(var i=0; i < rs.rows.length; i++) {
    		    	result[i] = rs.rows.item(i);
    		    }
    		}
    		
    		console.log(result);
    		
    		$.ajax({
				type: "POST",
				url: "/OnOffLine/blog.do?method=jsonParse",
				data: { "blogs" : result
				},
				success: function(data){
					console.log(data);
				},
				error: function(data){
					console.log(data);
				}
			});
    		
    		//success(result); //toss the result into the 'success' callback
        });
    });
}


function updateBlog(id, title, description, callback) {
	if (dbSupport){		
		db.transaction(function(tx) {
			tx.executeSql("UPDATE blogs SET title = ?, description = ? WHERE id = ?", [title, description, id], callback);
		});
	}
}

function deleteBlog(id, callback){
	if (dbSupport){
		db.transaction(function(tx) {
			console.log('deleteStart');
			//tx.executeSql("DELETE FROM blogs WHERE ID=?", [id], callback);
			tx.executeSql("UPDATE blogs SET isDeleted = 1 WHERE id=?", [id], callback);
			console.log('deleteEnd');
		});
	}
}

function renderResults(tx, rs) {
    e = $('.blogs');
    var template = $('.blog-template').html();        
    
    e.html("");

    if (rs !== null)
    {
        for(var i=0; i < rs.rows.length; i++) {
        	r = rs.rows.item(i);
          
        	e.html(e.html() + template);
          
        	$(e).find('.title').last().html(r['title']);
        	$(e).find('.description').last().html(r['description']);
          
        	var id = r['id'];
        	var date = moment(new Date(r['createdAt']));
        	$(e).find('.date').last().append(date.format("MMMM D, YYYY h:m A"));
        	
        	$(e).find('input[name=id]').last().val(id);
        	var href = $(e).find('a.view-link').last().attr('href') + id;
        	$(e).find('a.view-link').last().attr('href', href);
        	
        	var editLink = $(e).find('a.edit').last().attr('href') + id;
        	$(e).find('a.edit').last().attr('href', editLink);
    	}
    }
    
    $(e).find('a.view-link').click(function(){
    	window.location.href = '/OnOffLine/jsp/view.jsp#some?id=' + $(this).find('input[name=id]').attr('value');
    	return false;
    });
}

function populateForm(tx, rs)
{
	e = $('#create_form form');
	if (rs !== null)
    {
		console.log(rs);
        for(var i=0; i < rs.rows.length; i++) {
        	r = rs.rows.item(i);
          
        	$(e).find('input[name=title]').val(r['title']);
        	$(e).find('textarea').val(r['description']);
    	}
    }
	
	console.log('no more records');
}

function renderBlogs(id, callback) {
	db.transaction(function(tx) {

		if (callback === undefined){
			callback = renderResults;
		}
		
    	if (!(id === undefined)) {
    		tx.executeSql('SELECT * FROM blogs WHERE isDeleted = 0 AND id = ?', [id], callback);
    	} else {
    		tx.executeSql('SELECT * FROM blogs', [], callback);
    	}
    });
}

$(function(){
	
	if (dbSupport){
		db = window.openDatabase("scores", "", "Previous Scores", 5*1024*1024);
	}
	
	$(document).ready(function() {
		if (window.openDatabase){
			db.transaction(function(tx) {
		    	tx.executeSql('CREATE TABLE IF NOT EXISTS blogs(id INTEGER PRIMARY KEY AUTOINCREMENT, idOriginal INTEGER, guid VARCHAR(32), title TEXT, description TEXT, createdAt DATATIME, authorId INTEGER, isDeleted BOOLEAN, isSync BOOLEAN)', []);
		    });
		}
	});
});